<template>
  <div>
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">煤气检测管理系统</h1>
	            <p class="sub-title">每一组检测数据都是安全的凭证，每一次管理记录都是责任的彰显，用规范守护燃气使用，让安心常伴左右</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增煤气信息' : '编辑煤气信息'"
      width="70%">
      <el-row :gutter="20">
        <el-col :span="16">
          <meiyibiao :concentration='ruleForm.concentration'/>
        </el-col>
        <el-col :span="8">
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="煤气信息编号" prop="gasId">
              <el-input v-model="ruleForm.gasId" :disabled="dialogType === 'edit'"></el-input>
            </el-form-item>
            <el-form-item label="物业ID" prop="propertyId">
              <el-input v-model="ruleForm.propertyId"></el-input>
            </el-form-item>
            <el-form-item label="浓度" prop="concentration">
              <el-input v-model.number="ruleForm.concentration"></el-input>
            </el-form-item>
            <el-form-item label="处理状态" prop="status">
              <el-select v-model="ruleForm.status" placeholder="请选择处理状态">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-select v-model="ruleForm.urgencyLevel" placeholder="请选择紧急程度">
                <el-option label="低" value="低"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="高" value="高"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 主内容区 -->
    <el-row>
      <el-row :gutter="20" style="width: 100%; margin-bottom: 15px;">
        <el-col :span="12">
          <el-select v-model="searchStatus" placeholder="请选择处理状态" style="width: 300px;">
            <el-option label="全部" value=""></el-option>
            <el-option label="已处理" value="已处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="未处理" value="未处理"></el-option>
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch" style="margin-left: 10px;">搜索</el-button>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <el-table 
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%"
        height="450" 
        :row-class-name="tableRowClassName">
        <el-table-column fixed prop="gasId" label="煤气信息编号" width="150" align="center"></el-table-column>
        <el-table-column prop="propertyId" label="物业ID" width="150" align="center"></el-table-column>
        <el-table-column prop="concentration" label="浓度" width="150" align="center"></el-table-column>
        <el-table-column prop="urgencyLevel" label="紧急程度" width="150" align="center"></el-table-column>
        <el-table-column prop="status" label="处理状态" width="240" align="center">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 10px; justify-content: center;">
              <span class="status-text">{{ row.status }}</span>
              <el-select v-model="row.status" @change="updateRowStatus(row)" placeholder="处理状态" style="width: 120px;">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row type="flex" style="margin-top: 15px;">
        <el-col :push="5">
          <!-- 分页 -->
          <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,10,20,50]" 
            :page-size="pageSize" 
            :total="tableData.length"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-col>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { post } from '@/utils/axios';
import Meiyibiao from './Meiyibiao.vue';

// 状态选项
const options = [
  { value: '未处理', label: '未处理' },
  { value: '处理中', label: '处理中' },
  { value: '已处理', label: '已处理' }
];

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // add 或 edit
const ruleFormRef = ref(null);

// 搜索相关
const searchStatus = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const tableData = ref([]);

// 表单数据和验证规则
const ruleForm = reactive({
  gasId: '',
  propertyId: '',
  concentration: '',
  urgencyLevel: '',
  status: ''
});

const rules = {
  gasId: [
    { required: true, message: '请输入煤气信息编号', trigger: 'blur' }
  ],
  propertyId: [
    { required: true, message: '请输入物业ID', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ],
  urgencyLevel: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ],
  concentration: [
    { required: true, message: '请输入浓度', trigger: 'blur' },
    // 使用正则表达式验证数字，支持整数和小数
    { pattern: /^[+-]?(\d+(\.\d*)?|\.\d+)$/, message: '请输入有效的数字（可包含小数）', trigger: 'blur' }
  ]
};

// 新增按钮点击事件
const handleAdd = () => {
  // 重置表单
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  // 清空表单数据
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = '';
  });
  dialogType.value = 'add';
  dialogVisible.value = true;
};

// 编辑按钮点击事件
const handleEdit = (row) => {
  // 重置表单
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  // 填充表单数据
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = row[key];
  });
  dialogType.value = 'edit';
  dialogVisible.value = true;
};

// 删除按钮点击事件
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除编号为 ${row.gasId} 的煤气信息吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    post('/sc/gasinfo/deleteById', { gasId: row.gasId }, (res) => {
      if (res.status === 1) {
        ElMessage.success('删除成功！');
        // 重新获取数据
        getAllData();
      } else {
        ElMessage.error('删除失败：' + (res.msg || '未知错误'));
      }
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 提交表单（新增或编辑）
const handleSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 调用新增接口
        post('/sc/gasinfo/add', ruleForm, (res) => {
          if (res.status === 1) {
            ElMessage.success('新增成功！');
            dialogVisible.value = false;
            getAllData();
          } else {
            ElMessage.error('新增失败：' + (res.msg || '未知错误'));
          }
        });
      } else {
        // 调用编辑接口
        post('/sc/gasinfo/updateById', ruleForm, (res) => {
          if (res.status === 1) {
            ElMessage.success('编辑成功！');
            dialogVisible.value = false;
            getAllData();
          } else {
            ElMessage.error('编辑失败：' + (res.msg || '未知错误'));
          }
        });
      }
    }
  });
};

// 更新行状态
const updateRowStatus = (row) => {
  const data = {
    gasId: row.gasId,
    status: row.status,
  };
  post('/sc/gasinfo/updateById', data, (res) => {
    if (res.status === 1) {
      ElMessage.success('修改成功！');
    } else {
      ElMessage.error('修改失败，请重试');
      // 失败时恢复原来的状态
      getAllData();
    }
  });
};

// 行样式
const tableRowClassName = ({ row }) => {
  const statusColorMap = {
    '未处理': 'red-row',
    '处理中': 'yellow-row',
  };
  return statusColorMap[row.status] || '';
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 搜索功能（仅按状态）
const handleSearch = () => {
  post('/sc/gasinfo/byStatus', {
    status: searchStatus.value
  }, (res) => {
    if (res.status === 1) {
      ElMessage.success('查询成功！');
      tableData.value = res.data;
      currentPage.value = 1; // 重置为第一页
    } else {
      ElMessage.error('未查询到数据，请重新查询');
      tableData.value = [];
    }
  });
};

// 获取所有数据
const getAllData = () => {
  post('/sc/gasinfo/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data;
    } else {
      ElMessage.error('获取数据失败，请刷新页面重试');
    }
  });
};

// 页面加载时获取所有数据
onMounted(() => {
  getAllData();
});
</script>

<style scoped>
	
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}
.el-table .red-row {
  background-color: #ffdddd; /* 浅红色 */
}

.el-table .yellow-row {
  background-color: #ffffcc; /* 浅黄色 */
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

div {
  width: auto;
}

.status-text {
  font-weight: 500;
  min-width: 60px;
}
</style>
